﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Hosting;
using System.IO;
using System.Net.Http.Headers;
using System.Web;

namespace Html5Video.Controllers
{
    public class VideoController : ApiController
    {
        private const string MimeType = "video/mp4";

        public VideoController() { }

        [HttpGet]
        [Route("api/video")]
        public HttpResponseMessage Video()
        {
            HttpResponseMessage response = null;
            string fullFilePath = HostingEnvironment.MapPath("/Media/test.mp4");
            if (Request.Headers.Range != null)
            {
                FileInfo fileInfo = new FileInfo(fullFilePath);
                FileStream sourceStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                long size = 1024*1024;
                RangeHeaderValue rangeHeaderValue;
                if (Request.Headers.Range.Ranges.FirstOrDefault().From.HasValue && (Request.Headers.Range.Ranges.FirstOrDefault().From.Value + size) < fileInfo.Length)
                {
                    rangeHeaderValue = new RangeHeaderValue(Request.Headers.Range.Ranges.FirstOrDefault().From.Value, Request.Headers.Range.Ranges.FirstOrDefault().From.Value + size);
                }
                else
                {
                    rangeHeaderValue = Request.Headers.Range;
                }
                response = new HttpResponseMessage(HttpStatusCode.PartialContent);
                response.Content = new ByteRangeStreamContent(sourceStream, rangeHeaderValue, MimeType);
            }
            else
            {
                FileStream sourceStream = File.Open(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                BufferedStream bs = new BufferedStream(sourceStream);
                response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(bs);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeType);
            }
            return response;
        }
    }
}
